package models

import (
	"context"
	"errors"
	"github.com/olivere/elastic/v7"
)

func EsInsert(index string, data Fruit10, id string) error {
	_, err := EsClient.Index().Index(index).Id(id).BodyJson(data).Do(context.Background())
	if err != nil {
		return errors.New("es添加失败")
	}
	return nil
}
func InquireEs(index string, high *elastic.Highlight, query elastic.Query, page, size int) (*elastic.SearchResult, error) {
	data, err := EsClient.Search().Index(index).Query(query).Highlight(high).From((page - 1) * size).Size(size).Do(context.Background())
	if err != nil {
		return nil, err
	}
	return data, nil
}
func EsIkIndex(index string) error {
	_, err := EsClient.CreateIndex(index).BodyString(
		`{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_analyzer": { 
          "tokenizer": "ik_max_word"
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "title": {
        "type": "text",
        "analyzer": "my_analyzer"
      }
    }
  }
}`,
	).Do(context.Background())
	if err != nil {
		return err
	}
	return nil
}

func GroupSort(index string) error{
	agg := elastic.NewTermsAggregation().Field("types.keyword").Size(10).OrderByCountDesc()
	res,err := EsClient.Search(index).Size(10).Aggregation("types.keyword",agg).Do(context.Background())
	if err != nil {
		return err
	}
	aggResult,found := res.Aggregations.Terms("types.keyword")
	if !found {
		return errors.New("Aggregations not found: types")
	}
	aggResult.
}

func ShowEs(index string, query elastic.Query) (*elastic.SearchResult, error) {
	res, err := EsClient.Search(index).Query(query).Do(context.Background())
	return res, err
}
